package com.qianfeng.qlm.handforireader.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.qianfeng.qlm.handforireader.R;
import com.qianfeng.qlm.handforireader.adapter.CategoryDetailAdapter;
import com.qianfeng.qlm.handforireader.model.Category;
import com.qianfeng.qlm.handforireader.model.CategoryDetail;
import com.qianfeng.qlm.handforireader.util.Constant;
import com.qianfeng.qlm.handforireader.util.UrlMaker;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CategoryDetailActivity extends ActionBarActivity implements
        AdapterView.OnItemClickListener,PullToRefreshBase.OnRefreshListener2 {

    private CategoryDetailAdapter mAdapter;
    private ArrayList<CategoryDetail> mData;

    private int pagenum = 0;

    private String str = "http://r.qingman.cc/comic.php?m=AndroidV2x&a=comiclistbytagid&version=2.4&apitime=1427101791851&uid=0&sign=19b2497d1be97af0ee0bfe70390a3216";
    private Category category;
    private RequestQueue mQueue;
    private PullToRefreshListView pullToRefreshListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category_detail);

        mQueue = Volley.newRequestQueue(this);

        ActionBar actionBar = getSupportActionBar();

        actionBar.setDisplayHomeAsUpEnabled(true);

        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        category = (Category) extras.getSerializable("category");
        actionBar.setTitle(category.getComic_tag_name());

        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.activity_category_pullToRefresh);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        pullToRefreshListView.setOnRefreshListener(this);

        ListView listView = pullToRefreshListView.getRefreshableView();

        mData = new ArrayList<>();
        mAdapter = new CategoryDetailAdapter(this, mData,mQueue);
        listView.setAdapter(mAdapter);
        getDetail(pagenum);
        listView.setOnItemClickListener(this);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId){
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void getDetail(final int pagenum){
        String url = UrlMaker.GetComicTypeList(category.getId(), "" + pagenum);
        Log.d("CategoryDetailActivity",url);
        JsonObjectRequest jsonRequest = new JsonObjectRequest(
                Request.Method.GET,
                url,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("comic_arr");
                            String json = jsonArray.toString();
                            Gson gson = new Gson();
                            List<CategoryDetail> list = new ArrayList<>();
                            list = Arrays.asList(gson.fromJson(json, CategoryDetail[].class));
                            if (mData != null && mData.size() > 0 && pagenum == 0){
                                mData.clear();
                            }
                            mData.addAll(list);
                            mAdapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("CategoryDetailActivity","error");
                    }
                }
        );
        mQueue.add(jsonRequest);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        CategoryDetail categoryDetail = mData.get(position-1);
        String url = UrlMaker.GetComicInfor(categoryDetail.getId());

        Log.d("url",url);

        Intent intent = new Intent(this,NewChapterActivity.class);
        Bundle args = new Bundle();
        args.putSerializable("comic",mData.get(position-1));
        intent.putExtras(args);
        intent.putExtra("url",url);
        intent.putExtra("name",mData.get(position-1).getComic_name());
        startActivity(intent);
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        pagenum = 0;
        getDetail(0);
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        pagenum += 20;
        getDetail(pagenum);
        pullToRefreshListView.onRefreshComplete();
    }
}
